﻿Imports System.Reflection

Namespace AboutDNN.DNNMVC

    Public Class BaseRouteUserControl
        Inherits DotNetNuke.Entities.Modules.PortalModuleBase

        Public Shared WithEvents RouteContent As Global.System.Web.UI.WebControls.PlaceHolder

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            Try

                App.Cache.Add(Params.ModuleId, ModuleId)

                ' Init MVC
                App.InitMVC()

                ' Execute the action
                Dim result = RouteHelper.ExecuteAction()

                ' Process the result
                ProcessResult(result)

            Catch ex As Exception
                App.HandleException(ex, False)
                LoadErrorView(ex)
            End Try

        End Sub

        Private Sub ProcessResult(ByVal result As ActionResult)
            Select Case result.Type
                Case ActionResult.ActionTypeEnum.View
                    RouteContent.Controls.Add(RouteHelper.LoadView(result.ViewPath, result.Data, Me.Page))

                Case ActionResult.ActionTypeEnum.Literal
                    RouteHelper.RenderLiteral(result.Data)

                Case ActionResult.ActionTypeEnum.Json
                    RouteHelper.RenderJson(result.Data)

            End Select
        End Sub

        Private Sub LoadErrorView(ByVal ex As Exception)
            ' Load the error view
            Dim returnUrl As String = App.MVCContext.Route.GetUrl
            Dim data = ErrorViewModel.Create(ex, App.MVCContext.Route.GetUrl)
            RouteContent.Controls.Add(RouteHelper.LoadView(App.ErrorViewPath, data, Me.Page))
        End Sub


        ''' <summary>
        ''' Gets the form name. Can be used by jquery (includes the pre #)
        ''' </summary>
        Public Function FormName() As String
            If Page.Form IsNot Nothing Then
                Return "#" & Page.Form.ClientID
            Else
                Return "#Form"
            End If
        End Function


    End Class


End Namespace